package jgo.plugins.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;

import jgo.Context;
import jgo.User;

public class SimpleHttpContext extends HttpContext {
	private HttpExchange exchange;
	private int statusCode = 200;
	private boolean responseSent = false;
	private User user;
	private Map<String, String> headers = new HashMap<>();
	private Map<String, String> cookies = new HashMap<>();

	// ... 其他现有方法 ...

	public SimpleHttpContext(HttpExchange exchange) {
		this.exchange = exchange;
	}

	// 你可能需要添加一个方法来设置cookies，比如：
	public void setCookie(String name, String value) {
		cookies.put(name, value);
	}

	public String getMethod() {
		return exchange.getRequestMethod();
	}

	public String getPath() {
		return exchange.getRequestURI().getPath();
	}

	public Context status(int statusCode) {
		this.statusCode = statusCode;
		return this;
	}


	public Context header(String name, String value) {
		exchange.getResponseHeaders().set(name, value);
		return this;
	}

	public void end() {
		if (!responseSent) {
			try {
				exchange.sendResponseHeaders(statusCode, -1);
			} catch (IOException e) {
				throw new RuntimeException("Error ending response", e);
			}
			responseSent = true;
		}
		exchange.close();
	}

	public String body() {
		try (InputStream inputStream = exchange.getRequestBody();
				ByteArrayOutputStream result = new ByteArrayOutputStream()) {
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer)) != -1) {
				result.write(buffer, 0, length);
			}
			return result.toString(StandardCharsets.UTF_8.name());
		} catch (IOException e) {
			throw new RuntimeException("Error reading request body", e);
		}
	}

	public boolean isResponseSent() {
		return responseSent;
	}
}